package zara

class ExecutorsService {
    
    static transactional = true
    def backgroundService

    def save(websites,userinfo,requests) {
        backgroundService.execute("开始异步处理", { 
            def websitesGroupByPerson = websites.groupBy{elem -> 
                elem.person
            }
            websitesGroupByPerson.each{ key,value ->
                User user = User.get(key.id)
                user.total = user.total - value.size()
                if (!user.save(flush:true)) {
                    user.errors.each {
                        println it
                    }
                }
            }
            

            User aUser = User.get(userinfo)
            def clentIpAddress = requests.getRemoteAddr();
            websites.each{
                Ip ip = new Ip();
                ip.source = aUser.username
                ip.address = clentIpAddress
                ip.person = aUser
                ip.sitePerson = it.person
                ip.success = true
                ip.website = it
                if (!ip.save(flush:true)) {
                    ip.errors.each {
                        println it
                    }
                }
            }
            aUser.total = aUser.total+websites.size()

            if (!aUser.save(flush:true)) {
                    aUser.errors.each {
                        println it
                    }
            }
            
        })
    }
}
